package com.andyliu.interceptor;

import com.andyliu.system.entity.User;
import com.andyliu.system.service.IUserService;
import com.andyliu.util.DateUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * ClassName: TokenInterceptor
 * Description: TODO
 * date: 2021/8/10 5:22 下午
 *
 * @author andyliu
 * @qq 115176513
 * @since JDK 1.8
 */
@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    private IUserService userService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.debug("interceptor url"+request.getRequestURL().toString());
        String authentication = request.getHeader("author");
        if(authentication==null){
            // 头中没有，判断cookie中是否包含有
            boolean flag = true;
            Cookie[] cookies = request.getCookies();
            for (int i = 0; i < cookies.length; i++) {
                Cookie c = cookies[i];
                if(c.getName().equals("token")){
                    authentication = c.getValue();
                    flag = false;
                }
            }
            if(flag) {
                response.sendRedirect("/index.html");
                return false;
            }
        }
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        log.info("token:"+authentication);
        String userId = JWT.decode(authentication).getAudience().get(0);
        User user = userService.getById(Integer.parseInt(userId));
        if(user==null){
            response.sendRedirect("/index.html");
            return false;
        }
        JWTVerifier build = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
        try {
            build.verify(authentication);
            String jwtToken = JWT.create().withAudience(user.getUserId().toString()).withExpiresAt(DateUtil.getTokenExpressTime())
                    .sign(Algorithm.HMAC256(user.getPassword()));
            Cookie cookie  = new Cookie("token",jwtToken);
            response.addCookie(cookie);
        }catch (Exception ex){
            response.sendRedirect("/index.html");
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
